package com.example.parallelandroid;

import androidx.annotation.NonNull;
import  androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.google.gson.Gson;
import com.mob.MobSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    EventHandler eventHandler;
    EditText edtPhone,edtCode;
    Button btnLogin,btnCode;
    TextView btnPasswordLogin;
    private SharedPreferences sharedPreferences;
    Timer timer;
    int count = 60;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            int tag = msg.what;
            switch (tag){
                case 1:
                    int arg = msg.arg1;
                    if(arg==1){
                        btnCode.setText("重新获取");
                        count = 60;
                        timer.cancel();
                        btnCode.setEnabled(true);
                    }else{
                        btnCode.setText(count+"");
                    }
                    break;
                case 2:
                    Toast.makeText(MainActivity.this,"获取短信验证码成功",Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Constant.logger.info("获取短信验证码: 失败");
                    Toast.makeText(MainActivity.this,"获取短信验证码失败",Toast.LENGTH_LONG).show();
                    break;
                case 4:
                    // 检查手机号是否存在
                    String phone = edtPhone.getText().toString().trim();
                    Constant.logger.debug("进入检查手机号的方法中 checkPhone");
                    checkPhone(phone);
                    break;
                case 5:
                    //跳转
                    Intent mainIntent = new Intent(MainActivity.this,MainFromActivity.class);
                    startActivity(mainIntent);
                    finish();
                    Constant.logger.info("Jump from MainActivity to MainFromActivity");
                    break;
                case 6:
                    Intent otherIntent = new Intent(MainActivity.this,SettingPasswordActivity.class);
                    startActivity(otherIntent);
                    finish();
                    Constant.logger.info("Jump from MainActivity to SettingPasswordActivity");
                    break;
                default:
                    break;
            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getSharedPreferences("user",
                MODE_PRIVATE);

        checkAutoLogin();

        MobSDK.submitPolicyGrantResult(true);

        getView();

        init();
    }
    //检查手机号是否已经存在
    private void checkPhone(String phone) {
        Constant.logger.info("向服务端传输userName检测手机号 开始 userName=" + phone);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"user/checkUserName?userName=" + phone)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输userName检测手机号: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                JSONObject jsonObject = null;
                try {
                    Gson gson = new Gson();
                    jsonObject = new JSONObject(json);
                    String code = jsonObject.getString("code");
                    String jsonStr = jsonObject.getString("data");
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    if(!("null".equals(jsonStr) || "".equals(jsonStr) || json == null)){
                        User user = gson.fromJson(jsonStr,User.class);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        Constant.logger.debug("userId = " + user.getUserId());
                        editor.putString("userId",user.getUserId());
                        editor.commit();
                    }
                    Message message = new Message();
                    if("200".equals(code)){
                        message.what = 5;
                        handler.sendMessage(message);
                    }else{
                        message.what = 6;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    private void checkAutoLogin() {
        Boolean isAutoLogin = sharedPreferences.getBoolean("isAutoLogin",false);

        if(isAutoLogin){
            Intent mainIntent = new Intent(MainActivity.this,MainFromActivity.class);
            startActivity(mainIntent);
            finish();
        }
    }

    private void getView() {
        edtPhone = findViewById(R.id.edt_phone);
        edtCode = findViewById(R.id.edt_code);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this::onClick);
        btnPasswordLogin = findViewById(R.id.password_login);
        btnPasswordLogin.setOnClickListener(this::onClick);
        btnCode = findViewById(R.id.btn_code);
        btnCode.setOnClickListener(this::onClick);
    }

    private void init(){
        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
// TODO 此处为子线程！不可直接处理UI线程！处理后续操作需传到主线程中操作！
                if (result == SMSSDK.RESULT_COMPLETE) {
//成功回调
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Message message = new Message();
                        message.what = 4;
                        handler.sendMessage(message);
//提交短信、语音验证码成功
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    } else if (event == SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE) {
//获取语音验证码成功
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {
//失败回调
                    Message message = new Message();
                    message.what = 3;
                    handler.sendMessage(message);
                } else {
//其他失败回调
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    public void onClick(View view) {
        String phone = "";
        String code = "";
        int id = view.getId();
        switch (id){
            case R.id.btn_code:
                phone = edtPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)){
                    //倒计时
                    CountdownStart();
                    getVerificationCode("86",phone);
                }else{
                    Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_login:
                SharedPreferences.Editor editor = sharedPreferences.edit();
                phone = edtPhone.getText().toString().trim();
                code = edtCode.getText().toString().trim();
                editor.putString("phone",phone);
                editor.commit();
                if (TextUtils.isEmpty(phone)){
                    Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }else if (TextUtils.isEmpty(code)){
                    Toast.makeText(this,"请输入验证码",Toast.LENGTH_LONG).show();
                }else{
                    SMSSDK.submitVerificationCode("86",phone,code);
                }
                break;
            case R.id.password_login:
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
                Constant.logger.info("Jump from MainActivity to LoginActivity");
        }
    }


    public static void getVerificationCode(String country, String phone){
        //获取短信验证码
        SMSSDK.getVerificationCode(country,phone);
    }

    //倒计时函数
    private void CountdownStart(){
        btnCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                message.arg1 = count;
                if(count!=0){
                    count--;
                }else {
                    return;
                }
                handler.sendMessage(message);
            }
        }, 1000,1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
// 使用完EventHandler需注销，否则可能出现内存泄漏
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}